//
//  KeyListenerPlugin.m
//  camera
//
//  Created by FXY on 2024/3/14.
//

#import "KeyListenerPlugin.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface KeyListenerPlugin()

@property (nonatomic, strong) FlutterMethodChannel *channel;

///获取当前音量
@property(nonatomic, assign) float currentVolume;

@property(nonatomic, assign) BOOL first;

@property(nonatomic, strong) MPVolumeView *volumeView;

@end

@implementation KeyListenerPlugin

+ (void)registerWithRegistrar:(nonnull NSObject<FlutterPluginRegistrar> *)registrar {
    BOOL sound = [[[NSUserDefaults standardUserDefaults] valueForKey:@"sound"] boolValue];
    if(sound) {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    } else {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:nil];
    }

    
    FlutterMethodChannel *volumnChannel =
        [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/key_listener"
                                    binaryMessenger:[registrar messenger]];
    KeyListenerPlugin *plugin = [[KeyListenerPlugin alloc] initWithChannel:volumnChannel];
    
    [registrar addMethodCallDelegate:plugin channel:volumnChannel];
}

+ (void)setSound:(BOOL)sound {
    [[NSUserDefaults standardUserDefaults] setBool:sound forKey:@"sound"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    if(sound) {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    } else {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:nil];
    }
}


- (instancetype)initWithChannel:(FlutterMethodChannel*)channel {
    if (self = [super init]) {
        _channel = channel;
        _first = true;
    }
    return self;
}


- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"initialize" isEqualToString:call.method]) {
      self.currentVolume = [self getCurrentVolume];
      // 创建一个 MPVolumeView 实例
//       self.volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(-100, -100, 10, 10)];
//      [[UIApplication sharedApplication].keyWindow addSubview:self.volumeView];
//      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged:) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
//      [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  } else if (([@"dispose" isEqualToString:call.method]) ) {
//      [self.volumeView removeFromSuperview];
//      [[NSNotificationCenter defaultCenter] removeObserver:self];
//      [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
  } else {
    result(FlutterMethodNotImplemented);
  }
}


- (void)volumeChanged:(NSNotification *)notification {
    if([notification.name isEqualToString:@"AVSystemController_SystemVolumeDidChangeNotification"]) {
        NSDictionary *userInfo = notification.userInfo;
        float changeVolume = [[userInfo valueForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
        if([[userInfo valueForKey:@"AVSystemController_AudioVolumeChangeReasonNotificationParameter"] isEqualToString:@"RouteChange"]) {
            return;
        }
        if(changeVolume == 1 || changeVolume > self.currentVolume) {
            [self.channel invokeMethod:@"onKeyDown" arguments:@(1)];
        } else {
            [self.channel invokeMethod:@"onKeyDown" arguments:@(0)];
        }
        self.currentVolume = changeVolume;
    }
}

- (float)getCurrentVolume {
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error = nil;
    [audioSession setActive:YES error:&error];
    if (error) {
        NSLog(@"Error setting audio session active: %@", error);
        return -1.0f;
    }
    
    float currentVolume = [audioSession outputVolume];
    return currentVolume;
}


@end
